package com.kedll.library.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 专辑帮助类
 *
 * @author Administrator
 */
public class AlbumHelper {
    private static AlbumHelper instance;
    private final String TAG = getClass().getSimpleName();
    Context context;
    private ContentResolver cr;
    /**
     * 缩略图列表
     */
    private HashMap<String, String> thumbnailList = new HashMap<>();
    /**
     * 专辑列表
     */
    private List<HashMap<String, String>> albumList = new ArrayList<>();
    private HashMap<String, Map<String, Object>> bucketList = new HashMap<>();
    /**
     * 是否创建了图片集
     */
    private boolean hasBuildImagesBucketList = false;
    /**
     * 构造相册索引
     */
    private String[] columns = new String[]{BaseColumns._ID, ImageColumns.BUCKET_ID,
            ImageColumns.PICASA_ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME,
            MediaColumns.TITLE, MediaColumns.SIZE, ImageColumns.BUCKET_DISPLAY_NAME};

    private AlbumHelper() {
    }

    public static AlbumHelper getInstance() {
        if (instance == null) {
            instance = new AlbumHelper();
        }
        return instance;
    }

    public void onDestroy() {
        instance = null;
        cr = null;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        if (this.context == null) {
            this.context = context;
            cr = context.getContentResolver();
        }
    }

    /**
     * 得到原图
     */
    void getAlbum() {
        String[] projection = {BaseColumns._ID, AlbumColumns.ALBUM, AlbumColumns.ALBUM_ART,
                AlbumColumns.ALBUM_KEY, AlbumColumns.ARTIST, AlbumColumns.NUMBER_OF_SONGS};
        Cursor cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, null,
                null, null);
        getAlbumColumnData(cursor);

    }

    /**
     * 从本地数据库中得到原图
     *
     * @param cur
     */
    private void getAlbumColumnData(Cursor cur) {
        try {
            if (cur.moveToFirst()) {
                int _id;
                String album;
                String albumArt;
                String albumKey;
                String artist;
                int numOfSongs;

                int _idColumn = cur.getColumnIndex(BaseColumns._ID);
                int albumColumn = cur.getColumnIndex(AlbumColumns.ALBUM);
                int albumArtColumn = cur.getColumnIndex(AlbumColumns.ALBUM_ART);
                int albumKeyColumn = cur.getColumnIndex(AlbumColumns.ALBUM_KEY);
                int artistColumn = cur.getColumnIndex(AlbumColumns.ARTIST);
                int numOfSongsColumn = cur
                        .getColumnIndex(AlbumColumns.NUMBER_OF_SONGS);

                do {
                    // Get the field values
                    _id = cur.getInt(_idColumn);
                    album = cur.getString(albumColumn);
                    albumArt = cur.getString(albumArtColumn);
                    albumKey = cur.getString(albumKeyColumn);
                    artist = cur.getString(artistColumn);
                    numOfSongs = cur.getInt(numOfSongsColumn);

                    // Do something with the values.
                    Log.i(TAG, _id + " album:" + album + " albumArt:"
                            + albumArt + "albumKey: " + albumKey + " artist: "
                            + artist + " numOfSongs: " + numOfSongs + "---");
                    HashMap<String, String> hash = new HashMap<String, String>();
                    hash.put("_id", _id + "");
                    hash.put("album", album);
                    hash.put("albumArt", albumArt);
                    hash.put("albumKey", albumKey);
                    hash.put("artist", artist);
                    hash.put("numOfSongs", numOfSongs + "");
                    albumList.add(hash);

                } while (cur.moveToNext());
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            cur.close();
        }

    }

    /**
     * 得到图片集
     *
     * @param refresh
     * @return
     */
    public ArrayList<Map<String, Object>> getImagesBucketList(boolean refresh) {
        if (refresh || (!hasBuildImagesBucketList)) {
            buildImagesBucketList();
        }
        ArrayList<Map<String, Object>> tmpList = new ArrayList<>();
        for (Entry<String, Map<String, Object>> entry : bucketList.entrySet()) {
            tmpList.add(entry.getValue());
        }
        return tmpList;
    }

    /**
     * 得到图片集
     */
    void buildImagesBucketList() {
        long startTime = System.currentTimeMillis();

        // 构造缩略图索引
        getThumbnail();

        try {
            // 得到一个游标
            Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, columns, null,
                    null, null);
            if (cur != null && cur.moveToFirst()) {
                // 获取指定列的索引
                int photoIDIndex = cur.getColumnIndexOrThrow(BaseColumns._ID);
                int photoPathIndex = cur.getColumnIndexOrThrow(MediaColumns.DATA);
                int photoNameIndex = cur
                        .getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
                int photoTitleIndex = cur.getColumnIndexOrThrow(MediaColumns.TITLE);
                int photoSizeIndex = cur.getColumnIndexOrThrow(MediaColumns.SIZE);
                int bucketDisplayNameIndex = cur
                        .getColumnIndexOrThrow(ImageColumns.BUCKET_DISPLAY_NAME);
                int bucketIdIndex = cur.getColumnIndexOrThrow(ImageColumns.BUCKET_ID);
                int picasaIdIndex = cur.getColumnIndexOrThrow(ImageColumns.PICASA_ID);
                // 获取图片总数
                int totalNum = cur.getCount();

                do {
                    String _id = cur.getString(photoIDIndex);
                    String name = cur.getString(photoNameIndex);
                    String path = cur.getString(photoPathIndex);
                    String title = cur.getString(photoTitleIndex);
                    String size = cur.getString(photoSizeIndex);
                    String bucketName = cur.getString(bucketDisplayNameIndex);
                    String bucketId = cur.getString(bucketIdIndex);
                    String picasaId = cur.getString(picasaIdIndex);

                    Log.i(TAG, _id + ", bucketId: " + bucketId + ", picasaId: "
                            + picasaId + " name:" + name + " path:" + path
                            + " title: " + title + " size: " + size
                            + " bucket: " + bucketName + "---");

                    Map<String, Object> bucket = bucketList.get(bucketId);
                    if (bucket == null) {
                        bucket = new HashMap<>();
                        bucketList.put(bucketId, bucket);
                        ArrayList<Map<String, Object>> imageList = new ArrayList<>();
                        bucket.put("imageList", imageList);
                        bucket.put("bucketName", bucketName);
                    }
                    if (bucket.get("count") == null) {
                        bucket.put("count", 0);
                    }
                    int count = Parse.getInstance().parseInt(bucket.get("count"));
                    bucket.put("count", ++count);
                    Map<String, Object> imageItem = new HashMap<>();
                    imageItem.put("imageId", _id);
                    imageItem.put("imagePath", path);
                    imageItem.put("thumbnailPath", thumbnailList.get(_id));
                    if (bucket.get("imageList") == null) {
                        ArrayList<Map<String, Object>> item = new ArrayList<>();
                        bucket.put("imageList", item);
                    }
                    ((List<Map<String, Object>>) bucket.get("imageList")).add(imageItem);

                } while (cur.moveToNext());
            }

            if (cur != null) {
                cur.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

//        for (Entry<String, Map<String, Object>> entry : bucketList.entrySet()) {
//            Map<String, Object> bucket = entry.getValue();
//            for (int i = 0; i < Parse.getInstance() .parseList(bucket.get("imageList")).size(); ++i) {
//                Map<String, Object> image = Parse.getInstance().parseList(bucket.get("imageList")).get(i);
//            }
//        }
        hasBuildImagesBucketList = true;
        long endTime = System.currentTimeMillis();
        Log.d(TAG, "use time: " + (endTime - startTime) + " ms");
    }

    /**
     * 得到缩略图
     */
    private void getThumbnail() {
        String[] projection = {BaseColumns._ID, Thumbnails.IMAGE_ID,
                Thumbnails.DATA};
        Cursor cursor = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection,
                null, null, null);
        getThumbnailColumnData(cursor);
    }

    /**
     * 从数据库中得到缩略图
     *
     * @param cur
     */
    private void getThumbnailColumnData(Cursor cur) {
        try {
            if (cur.moveToFirst()) {
                int _id;
                int image_id;
                String image_path;
                int _idColumn = cur.getColumnIndex(BaseColumns._ID);
                int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);
                int dataColumn = cur.getColumnIndex(Thumbnails.DATA);

                do {
                    // Get the field values
                    _id = cur.getInt(_idColumn);
                    image_id = cur.getInt(image_idColumn);
                    image_path = cur.getString(dataColumn);

                    // Do something with the values.
                    // Log.i(TAG, _id + " image_id:" + image_id + " path:"
                    // + image_path + "---");
                    // HashMap<String, String> hash = new HashMap<String,
                    // String>();
                    // hash.put("image_id", image_id + "");
                    // hash.put("path", image_path);
                    // thumbnailList.add(hash);
                    thumbnailList.put("" + image_id, image_path);
                } while (cur.moveToNext());
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            cur.close();
        }

    }

    /**
     * 得到原始图像路径
     *
     * @param imageId
     * @return
     */
    String getOriginalImagePath(String imageId) {
        String path = null;
        Log.i(TAG, "---(^o^)----" + imageId);
        String[] projection = {BaseColumns._ID, MediaColumns.DATA};
        Cursor cursor = cr.query(Media.EXTERNAL_CONTENT_URI, projection,
                BaseColumns._ID + "=" + imageId, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));

        }
        return path;
    }

}
